package global.com.loansapplication.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.FloatRange;


import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import global.com.loansapplication.comm.MyApplication;

/**
 * Created by xuweihua on 16/6/14.
 */
public class BitmapUtils {

    /**
     * 缩放bitmap
     * @param context
     * @param scale
     * @param resId
     * @return
     */
    public static Bitmap getScaleBitmap(Context context, @FloatRange(from = 0.0f,to = 1.0f) float scale, int resId) {
        BitmapDrawable mBitmapDrawable = (BitmapDrawable) context.getResources().getDrawable(resId);
        Bitmap mBitmap = mBitmapDrawable.getBitmap();
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(scale, scale);
        Bitmap mScaleBitmap = Bitmap.createBitmap(mBitmap, 0, 0, width, height, matrix, true);
        return mScaleBitmap;
    }

    /**
     * 生成二维码
     */
//    public static Bitmap getCodeBitmap(String code, int width, int height) {
//        Bitmap bitmap=EncodingUtils.createQRCode(code, width, height, null);
//        Bitmap useful=ratio(bitmap,400,400);
//        if(bitmap!=null) {
//            bitmap.recycle();
//        }
//        return useful;
//    }

    /**
     * Compress image by size, this will modify image width/height. Used to get
     * thumbnail
     *
     * @param image
     * @param pixelW
     *            target pixel of width
     * @param pixelH
     *            target pixel of height
     * @return
     */
    public static Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, os);
        if (os.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            os.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, os);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
        float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        is = new ByteArrayInputStream(os.toByteArray());
        bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        // 压缩好比例大小后再进行质量压缩
        // return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
        return bitmap;
    }

    /**
     * 保存bitmap(.jpg)
     */
    public static String saveBitmap(String fileName, Bitmap bitmap){
        File cache=new File(MyApplication.imgPath+ File.separator+MyApplication.IMAGE_PIPELINE_CACHE_DIR);
        File file=new File(MyApplication.imgPath+ File.separator+MyApplication.IMAGE_PIPELINE_CACHE_DIR+ File.separator+fileName+".jpg");
        BufferedOutputStream out;
        try {
            if (!cache.exists()){
                cache.mkdirs();
            }
            if(!file.exists()){
                file.createNewFile();
            }
            out=new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }
}
